import smtplib, socket
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from setting import *


class EmailModel:
    def __init__(self):
        self.user = EMAIL_USER
        self.password = EMAIL_PASSWORD
        self.receivers = EMAIL_RECEIVERS
        self.device = f'{socket.gethostname()} -> {socket.gethostbyname(socket.gethostname())}'

    def send_email(self, info, title):
        # 三个参数：第一个为文本内容，第二个 plain 设置文本格式，第三个 utf-8 设置编码
        message = MIMEText(info, 'plain', 'utf-8')
        message['From'] = Header(self.device, 'utf-8')  # 发送者
        message['To'] = Header("spider_engineer", 'utf-8')  # 接收者
        message['Subject'] = Header(title, 'utf-8')
        try:
            with SMTP_SSL(host="smtp.exmail.qq.com", port=465) as smtp:
                # 登录发邮件服务器
                smtp.login(user=self.user, password=self.password)
                # 实际发送、接收邮件配置
                smtp.sendmail(from_addr=self.user, to_addrs=self.receivers, msg=message.as_string())
            print('邮件发送成功')
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")


if __name__ == '__main__':
    e = EmailModel()
    e.send_email('test')
